package com.yishe.utils;

import com.yishe.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * @author : chusifeng
 * @version :
 * @date :Create in 2021/4/9 15:53
 * @description: 通用工具类
 * @package com.yishe.utils
 * @className CommonUtils
 */
@Slf4j
public class CommonUtils {
    /**
     * key值定义
     **/
    public static final String GENERATE_KEY = "GAK";
    private static final String WXACCOUNFPROFIX = "WX_";
    private static final String RANDOMSTR = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789_-";

    public static boolean isRead(HttpServletRequest httpRequest) {
        // 请求的类型【POST,GET】
        String methodType = httpRequest.getMethod();
        // 上下文url
        String servletPath = httpRequest.getRequestURI().toString();
        /** methodType必须是 POST且servletPath中没有包括去除地址 **/
        if (RequestMethod.POST.name().equals(methodType)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取body流数据
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static String getBodyString(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));

            char[] bodyCharBuffer = new char[1024];
            int len = 0;
            while ((len = reader.read(bodyCharBuffer)) != -1) {
                sb.append(new String(bodyCharBuffer, 0, len));
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw e;
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw e;
                }
            }
        }
        return sb.toString();
    }

    /**
     * 获取全局唯一编码值<br>
     */
    public static Serializable getUUID() {
        Date endTime = getTodayEndTime(); // 当前结束时间
        /**
         * 1. 生成唯一序号（每天重复从1开始）
         */
        Long redisNum = RedisUtils.getInstance().generate(GENERATE_KEY, endTime);
        /**
         * 2. 序号补充时间信息且序列号
         */
        Serializable seriNum = generate(redisNum);

        return seriNum;
    }

    /**
     * 将整型数字左补0使获得8位字符串
     *
     * @param intval 需要填充的整数
     * @return 左补零后的8位字符串
     */
    private static String format(Long intval) {
        int i8 = 8;
        String formatted = Long.toHexString(intval);
        StringBuffer buf = new StringBuffer("00000000");
        buf.replace(i8 - formatted.length(), i8, formatted);
        return buf.toString();
    }

    private static String getTimer() {
        Date now = new Date();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String str = dateformat.format(now);
        return str;
    }

    /**
     * 生成UUID的方法，
     *
     * @return 可序列化实例 ，如果过程中有任何错误则返回"",即空字符串。
     */
    private static Serializable generate(Long number) {
        StringBuffer numberBuffer = new StringBuffer(25).append(getTimer()).append(format(number));
        log.info("获取唯一编码为：{}", numberBuffer);
        return numberBuffer;
    }

    /**
     * create by: chusifeng
     * Create in 2021/4/9 15:56
     * Description:获取当天结束时间
     * <p>Example</p>
     */
    public static Date getTodayEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }

    /**
     * 人不多，先用着
     */
    public static String createWxAccount() {
        String mill = DateUtil.getNow(DateUtil.HHMMSSS);
        return WXACCOUNFPROFIX + mill;
    }

    /**
     * 根据传入的长度，输出输入的length内的随机长度
     *
     * @param length
     * @return
     */
    public static String getRandomByLength(int length) {
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(WXACCOUNFPROFIX);
        int stringLength = (int) (Math.random() * length);
        for (int j = 0; j < stringLength; j++) {
            int index = random.nextInt(RANDOMSTR.length());
            char c = RANDOMSTR.charAt(index);
            stringBuffer.append(c);
        }
        return stringBuffer.toString() + getUUID().toString().substring(0, 10);
    }

    public static String getToken() {
        String seriNum = getUUID().toString();
        return getRandomByLength(40) + seriNum.substring(0, 10) + seriNum.substring(10);
    }
}
